package com.ruoyi.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import org.apache.commons.lang3.StringUtils;

public class QueryWrapperUtils {
    public QueryWrapperUtils() {
    }

    public static <T> LambdaQueryWrapper<T> wrapperLike(LambdaQueryWrapper<T> queryWrapper, String searchKey, SFunction<T, ?>... fieldNames) {
        if (fieldNames != null && fieldNames.length != 0 && !StringUtils.isBlank(searchKey)) {
            String[] searchKeyArr = searchKey.split(" ");

            for(String key : searchKeyArr) {
                if (!StringUtils.isBlank(key)) {
                    queryWrapper.and((wrapper) -> {
                        for(int i = 0; i < fieldNames.length; ++i) {
                            if (!StringUtils.isBlank(key)) {
                                ((LambdaQueryWrapper)wrapper.or()).like(fieldNames[i], key);
                            }
                        }

                    });
                }
            }

            return queryWrapper;
        } else {
            return queryWrapper;
        }
    }

    public static <T> QueryWrapper wrapperLike(QueryWrapper<T> ew, String searchKey, String... columNames) {
        if (columNames != null && columNames.length != 0) {
            if (StringUtils.isNotBlank(searchKey)) {
                String[] searchKeyArr = searchKey.split(" ");

                for(String key : searchKeyArr) {
                    if (!StringUtils.isBlank(key)) {
                        ew.and((wrapper) -> {
                            for(int i = 0; i < columNames.length; ++i) {
                                String column = columNames[i];
                                ((QueryWrapper)wrapper.or()).like(StringUtils.isNotBlank(key), column, key);
                            }

                        });
                    }
                }
            }

            return ew;
        } else {
            return ew;
        }
    }
}
